<template>
    <Breadcrumb :datas="[`管理系统`, `用户管理`]">
        <el-button plain @click="adddrawer.show = true" type="primary"
            ><el-icon><Plus /></el-icon>新增用户</el-button
        >
    </Breadcrumb>
    <el-table :data="users" style="width: 100%" empty-text="没有数据">
        <el-table-column label="用户">
            <template #default="scope">
                <div class="user-info">
                    <div class="avatar">
                        <img :src="scope.row.avatar" alt="" />
                    </div>
                    <div class="name">{{ scope.row.username }}</div>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="注册IP地址">
            <template #default="scope">
                {{ scope.row.regLocation.country }}-{{
                    scope.row.regLocation.region
                }}-{{ scope.row.regLocation.city }}
            </template>
        </el-table-column>
        <el-table-column label="最近登录" prop="lastLogin" />
        <el-table-column label="状态">
            <template #default="scope">
                <el-tag v-if="scope.row.isActive" type="success">已启用</el-tag>
                <el-tag type="danger" v-else>已禁用</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="下载与评分">
            <template #default="scope">
                <el-space size="large">
                    <el-link
                        type="primary"
                        @click="
                            router.replace(`/users/${scope.row._id}/downloads`)
                        "
                    >
                        <el-icon><Link /></el-icon>下载列表
                    </el-link>
                    <el-link
                        type="primary"
                        @click="
                            router.replace(`/users/${scope.row._id}/ratings`)
                        "
                    >
                        <el-icon><Link /></el-icon>评分列表
                    </el-link>
                </el-space>
            </template>
        </el-table-column>
        <el-table-column align="right" width="320">
            <template #header>
                <el-input
                    v-model.trim="params.keywords"
                    placeholder="请输入搜索关键词"
                    @keyup.enter="searchHandle"
                    clearable
                    @clear="searchHandle"
                    size="large"
                >
                    <template #append>
                        <el-button
                            @click="searchHandle"
                            size="large"
                            plain
                            type="primary"
                            >搜索</el-button
                        >
                    </template>
                </el-input>
            </template>
            <template #default="scope">
                <el-switch
                    size="large"
                    style="margin-right: 10px"
                    v-model="scope.row.isActive"
                    inline-prompt
                    :active-value="false"
                    :inactive-value="true"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="updateStatus(scope.row)"
                ></el-switch>
                <el-button type="warning" plain @click="showUpdate(scope.row)"
                    >修改</el-button
                >
                <DeleteConfirm :confirm="() => deleteEvent(scope.row._id)" />
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
            :page-size="params.pagesize"
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="params.pageno"
            :hide-on-single-page="true"
            @current-change="(page) => pageChange(page)"
        />
    </div>
    <Teleport to="body">
        <!-- 用户新增 -->
        <AddDrawer :show="adddrawer.show" title="新增用户" :close="closeDrawer">
            <template #body>
                <el-form-item label="用户名" size="large">
                    <el-input
                        type="text"
                        placeholder="请输入用户名"
                        size="large"
                        v-model.trim="adddrawer.data.username"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item label="密码" size="large">
                    <el-input
                        type="password"
                        show-password
                        placeholder="请输入密码"
                        size="large"
                        v-model.trim="adddrawer.data.password"
                        :prefix-icon="Lock"
                    />
                </el-form-item>
                <el-form-item label="用户头像" size="large">
                    <Uploader ref="addUploader" />
                </el-form-item>
            </template>
            <template #footer>
                <el-button size="large" @click="closeDrawer">取消</el-button>
                <el-button size="large" @click="addUserHandle" type="primary"
                    >提交</el-button
                >
            </template>
        </AddDrawer>
        <!-- 用户编辑 -->
        <el-dialog
            v-model="updatepop.show"
            align-center
            width="500"
            class="update-dialog"
            title="用户修改"
        >
            <el-form label-width="80px" label-position="top">
                <el-form-item label="用户名" size="large">
                    <el-input
                        type="text"
                        placeholder="请输入用户名"
                        size="large"
                        disabled
                        v-model.trim="updatepop.user.username"
                        :prefix-icon="User"
                    />
                </el-form-item>
                <el-form-item label="密码" size="large">
                    <el-input
                        type="password"
                        show-password
                        placeholder="请输入密码"
                        size="large"
                        v-model.trim="updatepop.user.upassword"
                        :prefix-icon="Lock"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button size="large" @click="updatepop.show = false"
                        >取消</el-button
                    >
                    <el-button @click="updateUser" size="large" type="primary"
                        >确定</el-button
                    >
                </el-form-item>
            </el-form>
        </el-dialog>
    </Teleport>
</template>

<script setup>
import { useRouter } from "vue-router";
import { User, Lock, Plus, Link } from "@element-plus/icons-vue";
import { ref, reactive, onMounted, nextTick } from "vue";
import { UserList, UserDelete, UserAdd, UserUpdate } from "@/api/users";
import Breadcrumb from "@/components/breadcrumb";
import AddDrawer from "@/components/drawer";
import DeleteConfirm from "@/components/confirm";
import Uploader from "@/components/uploader";
import { ElMessage, ElNotification } from "element-plus";

const router = useRouter();
const updatepop = reactive({
    show: false,
    user: {}
});
const addUploader = ref(null);
const adddrawer = reactive({
    show: false,
    data: {
        username: "",
        password: ""
    }
});
const users = ref([]);
const total = ref(0);
const params = reactive({
    pageno: 1,
    pagesize: 10,
    keywords: ""
});

onMounted(() => {
    getUsers();
});
// 获取用户列表
const getUsers = async () => {
    const res = await UserList({
        pageno: params.pageno,
        pagesize: params.pagesize,
        keywords: params.keywords
    });
    if (res) {
        total.value = res.total * 1;
        users.value = res.list;
    }
};

// 搜索
const searchHandle = () => {
    params.pageno = 1;
    getUsers();
};
// 分页
const pageChange = (pageno) => {
    params.pageno = pageno;
    getUsers();
};
// 删除用户
const deleteEvent = async (id) => {
    const res = await UserDelete(id);
    if (res) {
        ElMessage.success("删除成功");
        users.value = users.value.filter((item) => item._id !== id);
        total.value--;
    }
};
// 修改用户
const showUpdate = (user) => {
    updatepop.show = true;
    updatepop.user = user;
};

// 确认修改
const updateUser = async () => {
    const res = await UserUpdate(updatepop.user._id, {
        password: updatepop.user.upassword
    });
    if (res) {
        ElMessage.success("修改成功");
        users.value.map((item) => {
            if (item._id === updatepop.user._id) {
                item.upassword = updatepop.user.upassword;
            }
        });
        updatepop.user = {};
        updatepop.show = false;
    }
};

// 关闭抽屉
const closeDrawer = () => {
    adddrawer.show = false;
};

// 添加用户
const addUserHandle = async () => {
    if (!adddrawer.data.username) {
        return ElMessage.error("请填写用户名");
    }
    if (!adddrawer.data.password) {
        return ElMessage.error("请填写用户密码");
    }
    if (!addUploader.value.getUrl()) {
        return ElMessage.error("请上传用户头像");
    }
    const res = await UserAdd({
        username: adddrawer.data.username,
        password: adddrawer.data.password,
        avatar: addUploader.value.getUrl()
    });
    if (res) {
        ElMessage.success("用户添加成功");
        users.value.unshift(res);
        adddrawer.show = false;
        adddrawer.data = {
            username: "",
            password: ""
        };
        addUploader.value.clearFiles();
        total.value++;
    }
};

// 修改状态
const updateStatus = async ({ _id, isActive }) => {
    const status = isActive ? true : false;
    const res = await UserUpdate(_id, { isActive: status });
    if (res) {
        ElMessage.success("用户状态修改成功");
        users.value.map((item) => {
            if (item._id == _id) {
                item.isActive = status;
            }
        });
    }
};
</script>

<style lang="scss" scoped>
.user-info {
    display: flex;
    align-items: center;
    .avatar {
        width: 40px;
        height: 40px;
        display: block;
        border-radius: 50%;
        overflow: hidden;
        border: 1px solid rgba(0, 0, 0, 0.5);
        margin-right: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: aquamarine;
        img {
            max-width: 100%;
            max-height: 100%;
        }
    }
}

.add-drawer {
    h1 {
        font-weight: bold;
        align-items: center;
    }
    .avatar,
    .upload {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        border: 1px solid #ddd;
        border-radius: 4px;
        position: relative;
        img {
            width: 100%;
        }
        .hover {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.5);
            display: flex;
            color: #ff0000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            .icon {
                cursor: pointer;
            }
        }
        &:hover .hover {
            opacity: 1;
        }
    }
    .upload {
        cursor: pointer;
    }
}
.update-dialog {
    .avatar,
    .upload {
        width: 100px;
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        border: 1px solid #ddd;
        border-radius: 4px;
        position: relative;
        img {
            width: 100%;
        }
        .hover {
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.5);
            display: flex;
            color: #ff0000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            .icon {
                cursor: pointer;
            }
        }
        &:hover .hover {
            opacity: 1;
        }
    }
    .upload {
        cursor: pointer;
    }
}
</style>
